package com.ad.backstage.service.impl;

import com.ad.backstage.common.enums.UserTypeEnum;
import com.ad.backstage.common.utils.BeanUtil;
import com.ad.backstage.common.utils.CosUploadUtils;
import com.ad.backstage.enums.MerchantStatusEnum;
import com.ad.backstage.mapper.*;
import com.ad.backstage.model.*;
import com.ad.backstage.service.IMerchantSystemService;
import com.ad.payload.constant.PicBusinessConstant;
import com.ad.payload.dto.MerchantDto;
import com.ad.payload.dto.merchant.ItemDetailPageDto;
import com.ad.payload.dto.merchant.MerchantKeyValueAddDto;
import com.ad.payload.dto.merchant.MerchantKeyValueEditDto;
import com.ad.payload.enums.ResultCode;
import com.ad.payload.model.*;
import com.ad.payload.util.StringUtil;
import com.ad.payload.vo.DetailKeyValue;
import com.ad.payload.vo.merchant.MerchantVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * @author:dxgong
 * @日期 2021/3/27 17:55
 * @注释
 */
@Service
@Slf4j
public class MerchantSystemServiceImpl implements IMerchantSystemService{

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private UploadRecordMapper uploadRecordMapper;

    @Autowired
    private MerchantDetailKeyValMapper merchantDetailKeyValMapper;

    @Autowired
    private PfCategoryMapper pfCategoryMapper;

    @Autowired
    private PfCategorySubMapper pfCategorySubMapper;

    /**
     * 根据unionId更新用户
     *
     * @param wxUser pojo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Integer> updateWxUserByUnionId(WxUser wxUser) {
        String unionId = wxUser.getUnionId();
        if(StringUtil.isBlank(unionId)){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请先登录!");
        }
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id", unionId);

        this.wxUserMapper.update(wxUser, queryWrapper);
        return ResultBean.success();
    }

    /**
     * 根据手机号码更新用户
     *
     * @param wxUser
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBean<Integer> updateWxUserByPhone(WxUser wxUser) {
        if(StringUtil.isBlank(wxUser.getPhone())){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请输入手机号码!");
        }
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", wxUser.getPhone());

        this.wxUserMapper.update(wxUser, queryWrapper);
        return ResultBean.success();
    }

    /**
     * 根据uuid查询商家
     *
     * @param uuid uuid
     */
    @Override
    public ResultBean<Merchant> queryMerchantByUuid(String uuid) {
        if(StringUtil.isBlank(uuid)){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请先登录!");
        }
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("uuid", uuid);

        List<Merchant> merchants = this.merchantMapper.selectList(queryWrapper);
        if(merchants.isEmpty()){
            return ResultBean.build(ResultCode.FAILED.getCode(), "查无此用户!");
        }
        Merchant merchant = merchants.get(0);
        return ResultBean.success(merchant);
    }

    /**
     * 根据 unionId 查询微信用户
     *
     * @param unionId unionId
     */
    @Override
    public ResultBean<WxUser> queryWxUserByUnionId(String unionId) {
        if(StringUtil.isBlank(unionId)){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请先登录!");
        }
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("union_id", unionId);

        List<WxUser> wxUsers = this.wxUserMapper.selectList(queryWrapper);
        if(wxUsers.isEmpty()){
            return ResultBean.build(ResultCode.FAILED.getCode(), "该用户不存在!");
        }
        WxUser wxUser = wxUsers.get(0);
        return ResultBean.success(wxUser);
    }

    /**
     * 根据 unionId 查询微信用户
     *
     * @param phone phone
     */
    @Override
    public ResultBean<WxUser> queryWxUserByPhone(String phone) {
        if(StringUtil.isBlank(phone)){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请输入手机号码!");
        }
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);

        List<WxUser> wxUsers = this.wxUserMapper.selectList(queryWrapper);
        if(wxUsers.isEmpty()){
            return ResultBean.build(ResultCode.FAILED.getCode(), "该用户不存在!");
        }
        WxUser wxUser = wxUsers.get(0);
        return ResultBean.success(wxUser);
    }

    /**
     * 根据 unionId 查询微信用户
     *
     * @param serviceOpenId serviceOpenId
     */
    @Override
    public ResultBean<WxUser> queryWxUserByServiceOpenId(String serviceOpenId) {
        if(StringUtil.isBlank(serviceOpenId)){
            return ResultBean.build(ResultCode.LOGIN_FAILED.getCode(), "请先登录!");
        }
        QueryWrapper<WxUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("service_open_id", serviceOpenId);

        List<WxUser> wxUsers = this.wxUserMapper.selectList(queryWrapper);
        if(wxUsers.isEmpty()){
            return ResultBean.build(ResultCode.FAILED.getCode(), "该用户不存在!");
        }
        WxUser wxUser = wxUsers.get(0);
        return ResultBean.success(wxUser);
    }

    /**
     * 添加商家详情
     *
     * @param merchantKeyValueAddDto
     */
    @Override
    public Long insertMerchantDetail(MerchantKeyValueAddDto merchantKeyValueAddDto) {
        MerchantDetailKeyVal merchantDetailKeyVal = new MerchantDetailKeyVal();
        BeanUtil.copyProperties(merchantKeyValueAddDto, merchantDetailKeyVal);
        merchantDetailKeyValMapper.insert(merchantDetailKeyVal);
        return merchantDetailKeyVal.getId();
    }

    /**
     * 修改商家详情
     *
     * @param merchantKeyValueEditDto
     */
    @Override
    public Long updateMerchantDetail(MerchantKeyValueEditDto merchantKeyValueEditDto) {
        MerchantDetailKeyVal merchantDetailKeyVal = new MerchantDetailKeyVal();
        BeanUtil.copyProperties(merchantKeyValueEditDto, merchantDetailKeyVal);
        merchantDetailKeyValMapper.updateById(merchantDetailKeyVal);
        return merchantKeyValueEditDto.getId();
    }

    /**
     * 删除详情
     *
     * @param idDto
     */
    @Override
    public Long deleteMerchantDetailById(IdDto idDto) {
        merchantDetailKeyValMapper.deleteById(idDto.getId());
        return idDto.getId();
    }

    /**
     * 查询详情列表
     *
     * @param itemDetailPageDto
     */
    @Override
    public List<DetailKeyValue> queryDetailKeyValueList(ItemDetailPageDto itemDetailPageDto) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.orderByDesc("id");
        queryWrapper.eq("merchant_id", itemDetailPageDto.getMerchantId());

        List list = merchantDetailKeyValMapper.selectList(queryWrapper);

        List<DetailKeyValue> rtnList = new ArrayList<>();
        list.forEach(item -> {
            DetailKeyValue detailKeyValue = new DetailKeyValue();
            MerchantDetailKeyVal merchantDetailKeyVal = (MerchantDetailKeyVal) item;
            detailKeyValue.setId(String.valueOf(merchantDetailKeyVal.getId()));
            detailKeyValue.setKey(merchantDetailKeyVal.getItemKey());
            detailKeyValue.setValue(merchantDetailKeyVal.getItemValue());
            rtnList.add(detailKeyValue);
        });

        return rtnList;
    }

    @Override
    public MerchantVo queryMerchantInfoByUuid(UuidDto uuidDto) {

        Merchant merchant = this.merchantMapper.queryMerchantInfoByUuid(uuidDto.getUuid());

        MerchantVo vo = new MerchantVo();
        BeanUtil.copyProperties(merchant, vo);

        vo.setDisplayArea(merchant.getProvinceName() + "->" + merchant.getCityName() + "->" + merchant.getDistrictName());

        if(UserTypeEnum.TYPE_0.getCode() == Integer.parseInt(merchant.getType())){
            vo.setDisplayType(UserTypeEnum.TYPE_0.getValue());
        } else if(UserTypeEnum.TYPE_1.getCode() == Integer.parseInt(merchant.getType())){
            vo.setDisplayType(UserTypeEnum.TYPE_1.getValue());
        } else if(UserTypeEnum.TYPE_2.getCode() == Integer.parseInt(merchant.getType())){
            vo.setDisplayType(UserTypeEnum.TYPE_2.getValue());
        } else if(UserTypeEnum.TYPE_3.getCode() == Integer.parseInt(merchant.getType())){
            vo.setDisplayType(UserTypeEnum.TYPE_3.getValue());
        } else if(UserTypeEnum.TYPE_4.getCode() == Integer.parseInt(merchant.getType())){
            vo.setDisplayType(UserTypeEnum.TYPE_4.getValue());
        } else if (UserTypeEnum.TYPE_5.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_5.getValue());
        } else if (UserTypeEnum.TYPE_6.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_6.getValue());
        } else if (UserTypeEnum.TYPE_DEFAULT.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_DEFAULT.getValue());
        } else if (UserTypeEnum.TYPE_7.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_7.getValue());
        } else if (UserTypeEnum.TYPE_8.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_8.getValue());
        } else if (UserTypeEnum.TYPE_9.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_9.getValue());
        } else if (UserTypeEnum.TYPE_10.getCode() == Integer.parseInt(merchant.getType())) {
            vo.setDisplayType(UserTypeEnum.TYPE_10.getValue());
        }

        return vo;
    }

    @Transactional
    @Override
    public Long delPic(@Valid MerchantImgDto merchantImgDto) {

        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ex_uuid", merchantImgDto.getUuid());

        Merchant merchant = this.merchantMapper.selectOne(queryWrapper);
        if("cover".equalsIgnoreCase(merchantImgDto.getFlag())){
            merchant.setExCoverIcon("");
        } else if ("env".equals(merchantImgDto.getFlag())){
            String envIcon = merchant.getExEnvIcon();
            envIcon = envIcon.replace(merchantImgDto.getPath(),"");
            if(envIcon.indexOf(",,") != -1){
                envIcon = envIcon.replace(",,",",");
            } else if(envIcon.startsWith(",")){
                envIcon = envIcon.substring(1,envIcon.length());
            } else if(envIcon.endsWith(",")){
                envIcon = envIcon.substring(0,envIcon.length()-1);
            }
            merchant.setExEnvIcon(envIcon);
        } else if ("open".equals(merchantImgDto.getFlag())){
            String openIcon = merchant.getExOpenIcon();
            openIcon = openIcon.replace(merchantImgDto.getPath(),"");
            if(openIcon.indexOf(",,") != -1){
                openIcon = openIcon.replace(",,",",");
            } else if(openIcon.startsWith(",")){
                openIcon = openIcon.substring(1,openIcon.length());
            } else if(openIcon.endsWith(",")){
                openIcon = openIcon.substring(0,openIcon.length()-1);
            }
            merchant.setExOpenIcon(openIcon);
        } else if ("identity".equals(merchantImgDto.getFlag())){
            String identityIcon = merchant.getExIdentityIcon();
            identityIcon = identityIcon.replace(merchantImgDto.getPath(),"");
            if(identityIcon.indexOf(",,") != -1){
                identityIcon = identityIcon.replace(",,",",");
            } else if(identityIcon.startsWith(",")){
                identityIcon = identityIcon.substring(1,identityIcon.length());
            } else if(identityIcon.endsWith(",")){
                identityIcon = identityIcon.substring(0,identityIcon.length()-1);
            }
            merchant.setExIdentityIcon(identityIcon);
        } else if ("bank".equals(merchantImgDto.getFlag())){
            String bankIcon = merchant.getExBankIcon();
            bankIcon = bankIcon.replace(merchantImgDto.getPath(),"");
            if(bankIcon.indexOf(",,") != -1){
                bankIcon = bankIcon.replace(",,",",");
            } else if(bankIcon.startsWith(",")){
                bankIcon = bankIcon.substring(1,bankIcon.length());
            } else if(bankIcon.endsWith(",")){
                bankIcon = bankIcon.substring(0,bankIcon.length()-1);
            }
            merchant.setExBankIcon(bankIcon);
        }

        this.merchantMapper.updateById(merchant);

        //更新图片表
        QueryWrapper<UploadRecord> upQueryWrapper = new QueryWrapper<>();
        upQueryWrapper.eq("business_id", merchant.getId());
        upQueryWrapper.eq("path", merchantImgDto.getPath());
        UploadRecord uploadRecord = new UploadRecord();
        uploadRecord.setDeleteStatus(1);
        this.uploadRecordMapper.update(uploadRecord, upQueryWrapper);

        return merchant.getId();
    }

    @Override
    public String uploadPic(MultipartFile file, String flag, String uuid) {
        String imagePath = "";
        if (file != null) {
            String[] names = file.getOriginalFilename().split("\\.");
            String fileName = CosUploadUtils.getRandomString(20) + "." + names[names.length-1];
            imagePath = CosUploadUtils.uploadFile(flag.toLowerCase(Locale.ENGLISH), flag.toLowerCase(Locale.ENGLISH) + "/" + fileName, file);

            //插入图片表（上传的图片都默认为没审核通过,状态未删除）
            QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("ex_uuid", uuid);
            Merchant merchant = this.merchantMapper.selectOne(queryWrapper);
            UploadRecord uploadRecord = new UploadRecord();
            uploadRecord.setBusinessId(merchant.getId());
            if("cover".equals(flag)){
                uploadRecord.setBusinessType("cover");
            } else if("env".equalsIgnoreCase(flag)){
                uploadRecord.setBusinessType("env");
            } else if("open".equalsIgnoreCase(flag)){
                uploadRecord.setBusinessType("open");
            } else if("identity".equalsIgnoreCase(flag)){
                uploadRecord.setBusinessType("identity");
            } else {
                uploadRecord.setBusinessType("bank");
            }
            Date date = new Date();
            uploadRecord.setPath(imagePath);
            uploadRecord.setCreateTime(date);
            uploadRecord.setUpdateTime(date);
            this.uploadRecordMapper.insert(uploadRecord);
        }
        return imagePath;
    }

    @Override
    public Long updateMerchantByUuid(@Valid MerchantDto merchantDto) {

        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ex_uuid", merchantDto.getUuid());
        Merchant model = this.merchantMapper.selectOne(queryWrapper);

        model.setExName(merchantDto.getName());
        model.setExPhone(merchantDto.getPhone());
        model.setExProvince(merchantDto.getProvince());
        model.setExCity(merchantDto.getCity());
        model.setExDistrict(merchantDto.getDistrict());
        model.setExAddress(merchantDto.getAddress());
        model.setExLongitude(merchantDto.getLongitude() + "");
        model.setExLatitude(merchantDto.getLatitude() + "");
        model.setExType(merchantDto.getType());
        model.setExDescription(merchantDto.getDescription());
        model.setExTown(merchantDto.getTown());
        model.setCategoryId(Long.valueOf(merchantDto.getFirstCategoryId()));
        model.setExCoverIcon(merchantDto.getExCoverIcon());
        model.setExEnvIcon(merchantDto.getExEnvIcon());
        model.setExOpenIcon(merchantDto.getExOpenIcon());
        model.setExIdentityIcon(merchantDto.getExIdentityIcon());
        model.setExBankIcon(merchantDto.getExBankIcon());
        if(StringUtil.isNotBlank(merchantDto.getSecondCategoryId())){
            model.setCategorySubId(Long.valueOf(merchantDto.getSecondCategoryId()));
        }
        if("examine".equalsIgnoreCase(merchantDto.getFlag())){
            model.setExExamineStatus(MerchantStatusEnum.STATUS_ON_CHECK.getCode());
            //更新商家待审核图片字段

            QueryWrapper<UploadRecord> upQueryWrapper = new QueryWrapper<>();
            upQueryWrapper.eq("business_id", PicBusinessConstant.MERCHANT_PIC + model.getId());
            upQueryWrapper.eq("delete_status", 0);
            List<UploadRecord> uploadRecords = this.uploadRecordMapper.selectList(upQueryWrapper);

            if(uploadRecords.size() > 0) {
                model.setExEnvIcon("");
                model.setExOpenIcon("");
                model.setExIdentityIcon("");
                model.setExBankIcon("");
                for (UploadRecord ur : uploadRecords) {
                    if ("cover".equals(ur.getBusinessType())) {
                        model.setExCoverIcon(ur.getPath());
                    } else if ("env".equalsIgnoreCase(ur.getBusinessType())) {
                        model.setExEnvIcon(StringUtils.isBlank(model.getExEnvIcon()) ? ur.getPath() : model.getExEnvIcon() + "," + ur.getPath());
                    } else if ("open".equalsIgnoreCase(ur.getBusinessType())){
                        model.setExOpenIcon(StringUtils.isBlank(model.getExOpenIcon()) ? ur.getPath() : model.getExOpenIcon() + "," + ur.getPath());
                    } else if ("identity".equalsIgnoreCase(ur.getBusinessType())){
                        model.setExIdentityIcon(StringUtils.isBlank(model.getExIdentityIcon()) ? ur.getPath() : model.getExIdentityIcon() + "," + ur.getPath());
                    } else {
                        model.setExBankIcon(StringUtils.isBlank(model.getExBankIcon()) ? ur.getPath() : model.getExBankIcon() + "," + ur.getPath());
                    }
                }
            }

        }

        this.merchantMapper.updateById(model);

        return model.getId();
    }

    /**
     * 根据Id查询商家一级目录名和二级目录名
     *
     * @param idDto
     */
    @Override
    public List<String> queryCategoryByMerchantId(IdDto idDto) {
        Merchant merchant = merchantMapper.selectById(idDto.getId());
        // 下标0是一级行业，下标1是二级行业
        List<String> nameList = new ArrayList<>();
        PfCategory pfCategory = pfCategoryMapper.selectById(merchant.getCategoryId());
        PfCategorySub pfCategorySub = pfCategorySubMapper.selectById(merchant.getCategorySubId());

        nameList.add(pfCategory.getCategoryName());
        if(pfCategorySub != null){
            nameList.add(pfCategorySub.getSubName());
        }
        return nameList;
    }

    @Override
    public Long updateImageWH(String uuid, Integer width, Integer height) {
        QueryWrapper<Merchant> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("ex_uuid", uuid);
        Merchant merchant = this.merchantMapper.selectOne(queryWrapper);
        merchant.setCoverWidth(width);
        merchant.setCoverHeight(height);

        this.merchantMapper.updateById(merchant);

        return merchant.getId();
    }


}
